package cn.quantgroup.rabbitmq.workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 消息生产者,采用默认的循环(round-robin)转发方式,不支持
 * 消息的持久化.不支持消息的重发,也不支持公平转发。完全基于MQ
 * 默认配置
 * Created by mingzhu on 2016/12/12.
 */
public class NewTask {
    private static final String QUEUE_NAME = "worker_queue";

    public static void main(String[] args) throws Exception{
        //创建连接工厂,设置连接地址，用户名，密码
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("admin");
        factory.setPassword("admin");
        //创建连接
        Connection connection = factory.newConnection();
        //通过连接创建信道,信道的创建和销毁代价比连接要小的多
        Channel channel = connection.createChannel();
        //设置队列是否持久化,默认设置为false.不开启持久化
        boolean durable = false;
        //声明队列
        channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
        //发送的消息体
        String message = getMessage(args);
        //发送消息,消息体格式为字节数组
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        //关闭连接和通道
        channel.close();
        connection.close();
    }

    /**
     * 解析命令行参数
     * @param args
     * @return
     */
    public static String getMessage(String[] args){
        if(args.length < 1){
            return "Hello, World!";
        }
        return joinStrings(args, " ");
    }

    /**
     * 使用指定分隔符对数组分割
     * @param args
     * @param delimiter
     * @return 拼接后的字符串
     */
    public static String joinStrings(String[] args, String delimiter){
        int length = args.length;
        if(length == 0){
            return "";
        }
        StringBuilder word = new StringBuilder(args[0]);
        for(int i = 1; i < length; i ++){
            word.append(delimiter).append(args[i]);
        }
        return word.toString();
    }
}
